﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Minestorm.Evolved.Scenes;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Minestorm.Evolved.Assets;
using Minestorm.Evolved.GameLogic;

namespace Minestorm.Evolved.SceneObjects
{
    public class MapBackground : SceneObject
    {
        private BasicTexturedEffect _effect;

        private StarField[] _starFields;

        public override void LoadContent()
        {
            var content = ObjectFactory.InstanceOf<IAssetManager>();

            _starFields = new StarField[]
            {
                new StarField(500, content.Load(Textures.SkySphere)),
                new StarField(450, content.Load(Textures.Space1)),
                new StarField(400, TextureHelper.Flip(content.Load(Textures.Space1), true, true))
            };

            _effect = content.Load(Effects.BasicTextured);

            base.LoadContent();
        }

        public override void UnloadContent()
        {
            foreach (var starField in _starFields)
                starField.UnloadContent();

            base.UnloadContent();
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            base.Update(gameTime);
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
        {
            _effect.Projection = Scene.Camera.Projection;
            _effect.View = Scene.Camera.View;

            _effect.World = Matrix.Identity;
            
            var rs = GraphicsDevice.RasterizerState ?? new RasterizerState();

            GraphicsDevice.RasterizerState = new RasterizerState()
            {
                CullMode = CullMode.CullClockwiseFace
            };

            foreach (var starField in _starFields)
            {
                _effect.Texture = starField.Texture;

                ((Effect)_effect).CurrentTechnique.Passes[0].Apply();

                GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, starField.Vertices, 0, 4, starField.IndexBuffer, 0, 2);
            }
            GraphicsDevice.RasterizerState = rs;

            base.Draw(gameTime);
        }
    }
}
